package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	// 日志
	private static final Logger LOG = Logger.getLogger(OrderServiceImpl.class);

	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Autowired
	private WorkBillRepository workBillRepository;

	@Override
	public void addOrder(Order order) {
		// 设置订单编号
		String orderNum = UUID.randomUUID().toString().replace("-", "");
		order.setOrderNum(orderNum);
		// 设置订单时间
		order.setOrderTime(new Date());
		// 设置订单状态 1表示未取件
		order.setStatus("1");
		// area状态改变 transient-persistent
		String sendProvince = order.getSendArea().getProvince();
		String sendCity = order.getSendArea().getCity();
		String sendDistrict = order.getSendArea().getDistrict();
		Area sendArea = areaRepository.findByProvinceAndCityAndDistrict(sendProvince, sendCity, sendDistrict);
		order.setSendArea(sendArea);

		String recProvince = order.getRecArea().getProvince();
		String recCity = order.getRecArea().getCity();
		String recDistrict = order.getRecArea().getDistrict();
		Area recArea = areaRepository.findByProvinceAndCityAndDistrict(recProvince, recCity, recDistrict);
		order.setRecArea(recArea);

		// 通过地址查找客户表中对应的定区id
		String fixedAreaId = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/findFixedAreaId")
				.query("address", order.getSendAddress()).type(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			// 关联快递员,保存订单
			addOrder(order, fixedArea);
			// 生成工单
			generateWorkBill(order);
			return;
		}

		// 遍历发件人区域的所有分区,通过关键字查找所属定区
		Set<SubArea> subareas = sendArea.getSubareas();
		if (subareas != null) {
			for (SubArea subArea : subareas) {
				if (order.getSendAddress().contains(subArea.getKeyWords())) {
					FixedArea fixedArea = subArea.getFixedArea();
					if (fixedArea != null) {
						// 关联快递员,保存订单
						addOrder(order, fixedArea);
						// 生成工单
						generateWorkBill(order);
						return;
					}
				}
			}
		}
		LOG.warn("手动分单");
		order.setOrderType("2");
		orderRepository.save(order);
	}

	@Override
	public Order findByNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

	// 生产工单,发送短信给快递员
	private void generateWorkBill(final Order order) {
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("content", "短信序号:" + smsNumber + ",取件地址:" + order.getSendAddress() + ",联系电话:"
						+ order.getSendMobile() + ",快递员骚话:" + order.getSendMobileMsg());
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
		workBillRepository.save(workBill);
		LOG.warn("已短信通知快递员取件");
	}

	// 抽取订单关联快递员代码
	private void addOrder(Order order, FixedArea fixedArea) {
		Set<Courier> couriers = fixedArea.getCouriers();
		if (couriers != null) {
			for (Courier courier : couriers) {
				if (!Character.valueOf('1').equals(courier.getDeltag())) {
					order.setCourier(courier);
					order.setOrderType("1");
					orderRepository.save(order);
					LOG.warn("地址匹配,自动分单成功");
				}
			}
		}
	}
}
